/*****************************************************************************
 *
 *                      HUSONG PROPRIETARY INFORMATION
 *
 *          The information contained herein is proprietary to HUSONG
 *           and shall not be reproduced or disclosed in whole or in part
 *                    or used for any design or manufacture
 *              without direct written authorization from HUSONG.
 *
 *            Copyright (c) 2015 by HUSONG.  All rights reserved.
 *
 *****************************************************************************/
package me.send.business.base.alipush;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.CloudpushMessageAndroidRequest;
import com.taobao.api.request.CloudpushMessageIosRequest;
import com.taobao.api.request.CloudpushNoticeAndroidRequest;
import com.taobao.api.request.CloudpushNoticeIosRequest;
import com.taobao.api.request.CloudpushPushRequest;
import com.taobao.api.request.OpenAccountTokenApplyRequest;
import com.taobao.api.response.CloudpushMessageAndroidResponse;
import com.taobao.api.response.CloudpushMessageIosResponse;
import com.taobao.api.response.CloudpushNoticeAndroidResponse;
import com.taobao.api.response.CloudpushNoticeIosResponse;
import com.taobao.api.response.CloudpushPushResponse;
import com.taobao.api.response.OpenAccountTokenApplyResponse;

/**
 * @author maxmin
 *
 * @date 2015年8月4日 下午3:39:08
 */
public class Push {
	private final static Logger logger = LoggerFactory.getLogger(Push.class
			.getName());
	// 用户端推送配置
	private final static String userAppKey = "23205578";
	private final static String userSecret = "302f6ae42b0a40f85e75abfe3b58896a";
	// 经纪人端推送配置
	private final static String brokerAppKey = "23210327";
	private final static String brokerSecret = "9769cd051ebabd16ff9001e2ef964910";

	private static String url = "http://gw.api.taobao.com/router/rest";

	public static final String TARGET_DEVICE = "device";
	public static final String TARGET_ACCOUNT = "account";
	public static final String TARGET_TAG = "tag";
	public static final String TARGET_ALL = "all";

	private static final Long TIME_OUT = 72L;

	private final static TaobaoClient userClient = new DefaultTaobaoClient(url,
			userAppKey, userSecret);
	private final static TaobaoClient brokerClient = new DefaultTaobaoClient(
			url, brokerAppKey, brokerSecret);

	/**
	 * ios发送消息
	 * 
	 * 推送用户端消息
	 * 
	 * @param body
	 * @param target
	 * @param targetValue
	 */
	public static void pushIOSMessage(TaobaoClient client, String body,
			String target, String targetValue) {
		CloudpushMessageIosRequest req = new CloudpushMessageIosRequest();
		try {
			req.setBody(body);
			req.setTarget(target);
			req.setTargetValue(targetValue);
			CloudpushMessageIosResponse response = client.execute(req);
			if (response.isSuccess()) {
				logger.info("push message is success!");
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("push message is error! error info is :"
					+ e.getMessage());
		}
	}

	/**
	 * ios 发送通知
	 * 
	 * @param summary
	 * @param target
	 * @param targetValue
	 */
	public static void pushIOSNotice(TaobaoClient client, String summary,
			String target, String targetValue) {
		CloudpushNoticeIosRequest req = new CloudpushNoticeIosRequest();
		req.setSummary(summary);
		req.setTarget(target);
		req.setTargetValue(targetValue);
		Map<String,Integer> param = new HashMap<String, Integer>();
		param.put("badge", 1);
		req.setExt(JSON.toJSONString(param));
		req.setEnv("DEV");
		try {
			CloudpushNoticeIosResponse response = client.execute(req);
			if (response.isSuccess()) {
				System.out.println("push  notice is success!");
				logger.info("push  notice is success!");
			} else {
				System.out.println("push  notice is fail!"+response.getMsg());
				logger.info("push  notice is fail!");
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("push notice is error! error info is :"
					+ e.getMessage());
		}
	}

	/**
	 * Android发送消息
	 * 
	 * 推送用户端消息
	 * 
	 * @param body
	 * @param target
	 * @param targetValue
	 */
	public static void pushAndroidMessage(TaobaoClient client, String body,
			String target, String targetValue) {
		CloudpushMessageAndroidRequest req = new CloudpushMessageAndroidRequest();
		try {
			req.setBody(body);
			req.setTarget(target);
			req.setTargetValue(targetValue);
			CloudpushMessageAndroidResponse response = client.execute(req);
			if (response.isSuccess()) {
				logger.info("push message is success!");
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("push message is error! error info is :"
					+ e.getMessage());
		}
	}

	/**
	 * Android 发送通知
	 * 
	 * @param summary
	 * @param target
	 * @param targetValue
	 */
	public static void pushAndroidNotice(TaobaoClient client, String summary,
			String target, String targetValue) {
		CloudpushNoticeAndroidRequest req = new CloudpushNoticeAndroidRequest();
		req.setSummary(summary);
		req.setTarget(target);
		req.setTitle(summary);
		req.setTargetValue(targetValue);
		// req.setEnv("DEV");
		try {
			CloudpushNoticeAndroidResponse response = client.execute(req);
			if (response.isSuccess()) {
				System.out.println("push  notice is success!");
				logger.info("push  notice is success!");
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("push notice is error! error info is :"
					+ e.getMessage());
			logger.info("push notice is error! error info is :"
					+ e.getMessage());
		}
	}

	/**
	 * 发送消息，高级接口
	 * 
	 * @param client
	 *            userClient：用户端发送消息，brokerClient:经纪人端发送消息
	 * @param body
	 *            消息内容
	 * @param summery
	 *            摘要
	 * @param title
	 *            标题
	 * @param target
	 *            推送目标
	 * @param targetValue
	 *            推送目标的值
	 */
	private static void push(TaobaoClient client, String body, String summery,
			String title, String target, String targetValue) {
		CloudpushPushRequest req = new CloudpushPushRequest();
		req.setTarget(target);// 推送目标: device:推送给设备;
								// account:推送给指定帐号,tag:推送给自定义标签; all: 推送给全部
		req.setTargetValue(targetValue);// 根据Target来设定，如Target=device, 则对应的值为
										// 设备id1,设备id2. 多个值使用逗号分隔.
		// req.setAndroidActivity("/store/...");//Android对应的activity,仅仅当androidOpenType=2有效
		// req.setAndroidExtParameters("{k:v}");//自定义的kv结构,开发者扩展用 针对android
		req.setAndroidMusic("default");// android通知声音
		req.setAndroidOpenType("1");// 点击通知后动作,1:打开应用 2: 打开应用Activity 3:打开 url
		// req.setAndroidOpenUrl("http://www.taobao.com");//Android收到推送后打开对应的url,仅仅当androidOpenType=3有效
		req.setAntiHarassDuration(8L);// 防打扰时长,取值范围为1~23
		req.setAntiHarassStartTime(1L);// 防打扰开始时间点,取值范围为0~23
		// req.setBatchNumber("0001");//批次编号,用于活动效果统计
		req.setBody(body);// 推送内容
		req.setDeviceType(3L);// 设备类型,取值范围为:0~3云推送支持多种设备,各种设备类型编号如下:I
								// OS设备:deviceType=1;
								// Andriod设备:deviceType=2;如果存在此字段,则向指定的设备类型推送消息。
								// 默认为全部(3);
		req.setIosBadge("1");// iOS应用图标右上角角标
		// req.setIosExtParameters("{k:v}");//如果ios要发到开发环境，需要设置
		req.setIosExtParameters("{\"_ENV_\",\"DEV\"}");// 大写！
		// req.setIosExtParameters("{\"_ENV_\",\"PRODUACT\"}");//大写！
		req.setIosMusic("default");
		req.setRemind(false);// 当APP不在线时候，是否通过通知提醒
		req.setStoreOffline(false);// 离线消息是否保存,若保存, 在推送时候，用户即使不在线，下一次上线则会收到
		req.setSummery(summery);// 通知摘要
		req.setTimeout(TIME_OUT);// 离线消息保存时长,取值范围为1~72,若不填,则表示不保存离线消息
		req.setTitle(title);
		try {
			CloudpushPushResponse response = client.execute(req);
			if (response.isSuccess()) {
				System.out.println("push message is success!");
				logger.info("push message is success!");
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("push message is error! error info is :"
					+ e.getMessage());
			logger.info("push message is error! error info is :"
					+ e.getMessage());
		}
	}

	/**
	 * 
	 * @param body
	 *            消息内容
	 * @param summery
	 *            摘要
	 * @param title
	 *            标题
	 * @param target
	 *            推送目标
	 * @param targetValue
	 *            推送目标的值
	 */
	public static void userPush(String body, String summery, String title,
			String target, String targetValue) {
		push(userClient, body, summery, title, target, targetValue);
	}

	/**
	 * 
	 * @param body
	 *            消息内容
	 * @param summery
	 *            摘要
	 * @param title
	 *            标题
	 * @param target
	 *            推送目标
	 * @param targetValue
	 *            推送目标的值
	 */
	public static void brokerPush(String body, String summery, String title,
			String target, String targetValue) {
		push(brokerClient, body, summery, title, target, targetValue);
	}

	/**
	 * 发送用户通知
	 * 
	 * @param summery
	 * @param target
	 * @param targetValue
	 */
	public static void userNotice(String summery, String target,
			String targetValue) {
		//api说明：如果是发送给全部的话需要分开给安卓和苹果分别发送，如果不是全部推送，只需要用一种推送即可
		if (TARGET_ALL.equals(target)) {
			pushIOSNotice(userClient, summery, target, targetValue);
			pushAndroidNotice(userClient, summery, target, targetValue);
		} else {
			pushIOSNotice(userClient, summery, target, targetValue);
		}
	}

	/**
	 * 发送用户通知
	 * 
	 * @param summery
	 * @param target
	 * @param targetValue
	 */
	public static void brokerNotice(String summery, String target,
			String targetValue) {
		//api说明：如果是发送给全部的话需要分开给安卓和苹果分别发送，如果不是全部推送，只需要用一种推送即可
		if (TARGET_ALL.equals(target)) {
			pushIOSNotice(brokerClient, summery, target, targetValue);
			pushAndroidNotice(brokerClient, summery, target, targetValue);
		}else {
			pushIOSNotice(brokerClient, summery, target, targetValue);
		}
	}

	private static String getToken(TaobaoClient client, Long openAccountId,
			String isvAccountId) {
		try {
			OpenAccountTokenApplyRequest req = new OpenAccountTokenApplyRequest();
			req.setTokenTimestamp(System.currentTimeMillis() + 1141367296);
			req.setOpenAccountId(openAccountId);
			req.setIsvAccountId(isvAccountId);
			req.setUuid(UUID.randomUUID().toString());
			req.setLoginStateExpireIn(1141367296L);
			OpenAccountTokenApplyResponse response = client.execute(req);
			System.out.println(response.isSuccess() + ","
					+ response.getData().getData());
			return response.getData().getData();

		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("push message is error! error info is :"
					+ e.getMessage());
			logger.info("push message is error! error info is :"
					+ e.getMessage());
		}
		return null;
	}

	public static String getUserToken(Long openAccountId, String isvAccountId) {
		return getToken(userClient, openAccountId, isvAccountId);
	}

	public static String getBrokerToken(Long openAccountId, String isvAccountId) {
		return getToken(brokerClient, openAccountId, isvAccountId);
	}
}
